// pages/map/index.js
import { config } from '~/config/index'
Page({
  data: {
    latitude: 28.213477, // 橘子洲位置的纬度
    longitude: 112.932376, // 橘子洲位置的经度
    markers: [
      {
        id: 1,
        latitude: 28.213477,
        longitude: 112.932376,
        name: '橘子洲',
      },
    ],
    scale: 15, // 缩放级别
    controls: [
      {
        id: 1,
        iconPath: '/images/location.png',
        position: {
          left: 10,
          top: 10,
          width: 30,
          height: 30,
        },
        clickable: true,
      },
    ],
    showLocation: true,
  },

  // 点击定位控件时触发
  onTapControl(e) {
    const { controlId } = e;
    if (controlId === 1) {
      this.mapCtx.moveToLocation();
    }
  },

  // 地图视野发生变化时触发
  onRegionChange(e) {
    console.log('视野发生变化：', e);
  },

  getCurrent() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('当前位置::', res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: [
            {
              id: 1,
              latitude: res.latitude,
              longitude: res.longitude,
            },
          ],
        })
      }
    })
  },

  // 获取智能硬件的位置
  async getSearchLoaction() {
    var url = 'https://apis.map.qq.com/ws/location/v1/network';
    wx.request({
      method: 'POST',
      url: url,
      data: { device_id: '862677060411693', key: config.mapApiKey, cellinfo: [{ mcc: 460, mnc: 0, lac: 24591, cellid: 56109954, rss: -50 }] }, success: (res) => {
        console.log('检索数据：', res.data);
        const { result } = res.data;
        console.log(result.address)
        if (result.address) {
          this.setData({
            ...result.location,
            markers: [
              {
                id: 1,
                latitude: result.location.latitude,
                longitude: result.location.longitude,
              },
            ],
          })
        } else {
          this.getCurrent()
        }
      }, fail: () => {
        this.getCurrent()
      }
    })
  },

  onShow() {
    this.getTabBar().init();
    this.getSearchLoaction()
  },

  // 页面加载完成时触发
  onReady() {
    // 获取地图上下文对象
    this.mapCtx = wx.createMapContext('map');
  },
});
